# !/usr/bin/env python
"""
    blueprint_project
    ~~~~~~~


    :Author: swq
    :Date: 2021/07/04 14:26 
"""
import json

from flask import Blueprint
from flask import jsonify, request, render_template
from flask_jsonrpc import JSONRPC
from flask_restful_swagger_2 import swagger
from api.project.swagger_models import Project as ProjectSwagger

from api import db, app
from api.project.models import Project
from flask_restful import Resource, Api

blueprint_project = Blueprint(name="project", import_name=__name__)
api = Api(blueprint_project)


@app.before_first_request
def before_first_request_func():
    db.drop_all()
    db.create_all()
    db.session.commit()


class ProjectApi(Resource):

    def get(self):
        page = request.args.get('page', 1, type=int)
        pagination = Project.query.paginate(page, per_page=10)
        messages = pagination.items
        return jsonify({'msg': [msg.to_dict() for msg in messages]})

    @swagger.doc({
        'tags': ['Project'],
        'description': 'Returns a Project',
        'parameters': [
            {
                'name': 'project name',
                'id': 'int',
            }
        ],
        'responses': {
            '200': {
                'description': 'User',
                'schema': ProjectSwagger,
                'examples': {
                    'application/json': {
                        'id': 1,
                        'name': 'somebody'
                    }
                }
            }
        }
    })
    def post(self):
        resp = {}
        data = request.json
        project_id = data.get('id')
        project_name = data.get('name')
        if not project_id:
            resp['error'] = "id required!"
            resp['code'] = '4001'
            return jsonify(resp)
        if not project_name:
            resp['error'] = "name required!"
            resp['code'] = '4001'
            return jsonify(resp)

        project = Project()
        project.id = project_id
        project.name = project_name
        project.save()

        return jsonify({'msg': 'success'})


api.add_resource(ProjectApi, '/project', endpoint='project_api')
